<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\Sms as Smslib;
use fast\Random;
use think\Db;
use think\Hook;

/**
 * 加盟平台
 *
 * @icon fa fa-circle-o
 */
class Apply extends Backend
{

    /**
     * Apply模型对象
     * @var \app\admin\model\Apply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Apply;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 审核
     */
    public function do_status()
    {
        $param = $this->request->param();
        if(!$param['id'] || !$param['status'])
            $this->error('非法操作');
        $data = $this->model->find($param['id']);
        if(empty($data))
            $this->error('数据不存在');
        if($data->status != 0)
            $this->error('请勿重复审核');
        $data->status = $param['status'];
        $data->applytime = time();
        $data->remark = $param['remark'];
        Db::startTrans();
        try {
            //审核通过后自动注册账户，并给用户发送登录地址、账号信息
            //生成后台账号
            $params['username'] = $data['mobile'];
            $params['mobile'] = $data['mobile'];
            $params['nickname'] = $data['name'];
            $params['salt'] = Random::alnum();
            $params['password'] = 'a123456q/';
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            $params['userid'] = $data['userid'];
            $admin = model('Admin');
            $result = $admin->isUpdate(false)->allowField(true)->save($params);
            if ($result === false) {
                exception($admin->getError());
            }
            //要判断下当前申请是拆解厂/检测厂
            $admin_group = $data->type == 0 ? [2] : [4];
            //过滤不允许的组别,避免越权
            $group = array_intersect($this->childrenGroupIds, $admin_group);
            if (!$group) {
                exception(__('The parent group exceeds permission limit'));
            }

            $dataset = [];
            foreach ($group as $value) {
                $dataset[] = ['uid' => $admin->id, 'group_id' => $value];
            }
            model('AuthGroupAccess')->allowField(true)->saveAll($dataset);
            //改变申请人为商家（暂时不需要，全部通过后台系统实现）
            //db('user')->where(['id' => $data->user_id])->update(['type' => 2, 'admin_id' => $admin->id]);
            //此处做发送短信通知申请人，后台地址、账号
            $mobile = $data->mobile;
            $event = 'pass';
            $last = Smslib::get($mobile, $event);
            if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
                exception(__('手机号不正确'));
            }
            $ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
            if ($last && time() - $last['createtime'] < 60) {
                exception(__('发送频繁'));
            }
            if (!Hook::get('sms_send')) {
                if ($ipSendTotal >= 5) {
                    exception(__('发送频繁'));
                }
            }
            if (!Hook::get('sms_send')) {
                exception(__('请在后台插件管理安装短信验证插件'));
            }
            $ret = \app\common\library\Sms::notice($mobile,['name'=>$data['name'],'phone'=>$params['username'],'password'=>'a123456q/'], 'SMS_485470764');
            if (!$ret) {
                $ret_again = \app\common\library\Sms::notice($mobile,['name'=>$data['name'],'phone'=>$params['username'],'password'=>'a123456q/'], 'SMS_485470764');
                if(!$ret_again)
                    exception(__('发送失败，请检查短信配置是否正确'));
            }
            $data->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('审核成功');
    }
}
